{% extends "base_no_nav.html" %}

{% block title %}参与抽奖 - 抽奖系统{% endblock %}

{% block content %}
<!-- 页面标题 -->
<div class="text-center mb-3">
    <h2 class="text-primary mb-1">抽奖系统</h2>
    <p class="text-muted small mb-0">请填写信息参与抽奖</p>
</div>

<div class="row justify-content-center">
    <div class="col-11 col-sm-10 col-md-8 col-lg-6 col-xl-5">
        <div class="card shadow">
            <div class="card-header bg-primary text-white text-center">
                <h4 class="mb-0"><i class="fas fa-dice me-2"></i>参与抽奖</h4>
                {% if lottery_active %}
                    <small class="text-light">第 {{ round_number }} 轮抽奖进行中</small>
                {% else %}
                    <small class="text-light">活动暂未开启</small>
                {% endif %}
            </div>
            <div class="card-body">
                {% if not lottery_active %}
                <div class="alert alert-warning text-center" role="alert">
                    <i class="fas fa-exclamation-triangle fa-2x mb-3"></i>
                    <h5>抽奖活动暂未开启</h5>
                    <p class="mb-3">请等待管理员开启活动</p>
                    <button class="btn btn-outline-primary" onclick="checkLotteryStatus()">
                        <i class="fas fa-sync-alt me-2"></i>刷新状态
                    </button>
                </div>
                {% else %}
                <form id="lotteryForm">
                    <div class="mb-3">
                        <label for="name" class="form-label">姓名 *</label>
                        <input type="text" class="form-control" id="name" name="name" 
                               placeholder="请输入您的姓名" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="gender" class="form-label">性别 *</label>
                        <select class="form-select" id="gender" name="gender" required>
                            <option value="">请选择性别</option>
                            <option value="男">男</option>
                            <option value="女">女</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label for="id_card" class="form-label">身份证号码 *</label>
                        <input type="text" class="form-control" id="id_card" name="id_card" 
                               placeholder="请输入18位身份证号码" maxlength="18" required>
                    </div>
                    
                    <div class="d-grid">
                        <button type="submit" class="btn btn-primary btn-lg">
                            <i class="fas fa-dice me-2"></i>开始抽奖
                        </button>
                    </div>
                </form>
                {% endif %}
            </div>
        </div>

        <!-- 抽奖结果显示区域 -->
        <div id="resultCard" class="card shadow mt-4" style="display: none;">
            <div class="card-header bg-success text-white text-center">
                <h5 class="mb-0"><i class="fas fa-gift me-2"></i>抽奖结果</h5>
            </div>
            <div class="card-body text-center">
                <div id="resultContent">
                    <!-- 结果内容将由JavaScript动态插入 -->
                </div>
            </div>
        </div>

        <!-- 活动状态检查区域 -->
        <div class="card shadow mt-4">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <span>活动状态：</span>
                    <span id="activityStatus" class="badge bg-secondary">检查中...</span>
                </div>
                <div class="mt-2">
                    <small class="text-muted">状态会实时更新</small>
                </div>
            </div>
        </div>
    </div>
</div>

{% endblock %}

{% block scripts %}
<script>
// 全局变量记录当前状态
let currentStatus = null;
let currentRound = null;

// 根据活动状态更新页面内容
function updatePageContent(isActive, roundNumber) {
    const cardHeader = document.querySelector('.card-header');
    const cardBody = document.querySelector('.card-body');
    
    if (!cardHeader || !cardBody) return;
    
    // 检查轮次是否发生变化
    const roundChanged = currentRound !== null && currentRound !== roundNumber;
    
    // 如果轮次发生变化，隐藏抽奖结果
    if (roundChanged) {
        console.log('轮次发生变化，从第', currentRound, '轮变为第', roundNumber, '轮，隐藏旧结果');
        hideOldLotteryResult();
    }
    
    // 如果状态没有变化且轮次没有变化，且表单已存在，不重新生成内容
    if (currentStatus === isActive && currentRound === roundNumber && document.getElementById('lotteryForm')) {
        return;
    }
    
    // 记录新状态和轮次
    currentStatus = isActive;
    currentRound = roundNumber;
    
    if (isActive) {
        // 隐藏之前可能显示的抽奖结果
        hideOldLotteryResult();
        
        // 活动进行中，显示抽奖表单
        cardHeader.innerHTML = `
            <h4 class="mb-0"><i class="fas fa-dice me-2"></i>参与抽奖</h4>
            <small class="text-light">活动进行中</small>
        `;
        
        cardBody.innerHTML = `
            <form id="lotteryForm">
                <div class="mb-3">
                    <label for="name" class="form-label">姓名 *</label>
                    <input type="text" class="form-control" id="name" name="name" 
                           placeholder="请输入您的姓名" required>
                </div>
                
                <div class="mb-3">
                    <label for="gender" class="form-label">性别 *</label>
                    <select class="form-select" id="gender" name="gender" required>
                        <option value="">请选择性别</option>
                        <option value="男">男</option>
                        <option value="女">女</option>
                    </select>
                </div>
                
                <div class="mb-3">
                    <label for="level" class="form-label">级别 *</label>
                    <input type="text" class="form-control" id="level" name="level" 
                           placeholder="请输入您的级别" required>
                </div>
                
                <div class="mb-3">
                    <label for="id_card" class="form-label">身份证号码 *</label>
                    <input type="text" class="form-control" id="id_card" name="id_card" 
                           placeholder="请输入18位身份证号码" maxlength="18" required>
                </div>
                
                <div class="d-grid">
                    <button type="submit" class="btn btn-primary btn-lg">
                        <i class="fas fa-dice me-2"></i>开始抽奖
                    </button>
                </div>
            </form>
        `;
        
        // 重新绑定表单事件
        bindFormEvents();
        
    } else {
        // 活动未开启，显示提示信息
        cardHeader.innerHTML = `
            <h4 class="mb-0"><i class="fas fa-dice me-2"></i>参与抽奖</h4>
            <small class="text-light">活动暂未开启</small>
        `;
        
        cardBody.innerHTML = `
            <div class="alert alert-warning text-center" role="alert">
                <i class="fas fa-exclamation-triangle fa-2x mb-3"></i>
                <h5>抽奖活动暂未开启</h5>
                <p class="mb-3">请等待管理员开启活动</p>
                <button class="btn btn-outline-primary" onclick="checkLotteryStatus()">
                    <i class="fas fa-sync-alt me-2"></i>刷新状态
                </button>
            </div>
        `;
    }
}

// 绑定表单事件
function bindFormEvents() {
    const lotteryForm = document.getElementById('lotteryForm');
    if (lotteryForm) {
        // 移除之前的事件监听器，避免重复绑定
        lotteryForm.removeEventListener('submit', handleFormSubmit);
        lotteryForm.addEventListener('submit', handleFormSubmit);
        
        // 身份证号码输入限制
        const idCardInput = document.getElementById('id_card');
        if (idCardInput) {
            idCardInput.addEventListener('input', function(e) {
                this.value = this.value.replace(/[^\dXx]/g, '').toUpperCase();
            });
        }
    }
}

// 表单提交处理函数
function handleFormSubmit(e) {
    e.preventDefault();
    console.log('表单提交事件触发');
    
    const formData = new FormData(this);
    const data = {
        name: formData.get('name') ? formData.get('name').trim() : '',
        gender: formData.get('gender') || '',
        level: formData.get('level') ? formData.get('level').trim() : '',
        id_card: formData.get('id_card') ? formData.get('id_card').trim() : ''
    };
    
    console.log('表单数据:', data);
    
    // 基础验证
    if (!data.name || !data.gender || !data.level || !data.id_card) {
        showToast('请填写完整信息', 'error');
        return;
    }
    
    // 身份证号码格式基础验证
    if (data.id_card.length !== 18) {
        showToast('身份证号码必须为18位', 'error');
        return;
    }
    
    // 提交抽奖请求
    const submitBtn = this.querySelector('button[type="submit"]');
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>抽奖中...';
    
    console.log('开始发送请求...');
    fetch('/lottery/participate', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data)
    })
    .then(response => {
        console.log('收到响应:', response.status);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(result => {
        console.log('抽奖结果:', result);
        if (result.success) {
            showLotteryResult(result, data.name);
        } else {
            console.log('显示错误信息:', result.message);
            showToast(result.message, 'error');
            submitBtn.disabled = false;
            submitBtn.innerHTML = '<i class="fas fa-dice me-2"></i>开始抽奖';
        }
    })
    .catch(error => {
        console.error('请求错误:', error);
        showToast('网络错误，请重试', 'error');
        submitBtn.disabled = false;
        submitBtn.innerHTML = '<i class="fas fa-dice me-2"></i>开始抽奖';
    });
}

// 显示抽奖结果
function showLotteryResult(result, userName) {
    const resultCard = document.getElementById('resultCard');
    const resultContent = document.getElementById('resultContent');
    
    resultContent.innerHTML = `
        <div class="mb-4">
            <i class="fas fa-trophy fa-4x text-warning"></i>
        </div>
        <h3 class="text-success mb-3">恭喜您，${userName}！</h3>
        <div class="alert alert-success border-0 shadow-sm">
            <h4 class="alert-heading">您抽中的号码是：</h4>
            <hr>
            <h2 class="mb-0 lottery-number">${result.lottery_number}</h2>
        </div>
        <p class="text-muted">${result.message}</p>
    `;
    
    resultCard.style.display = 'block';
    document.getElementById('lotteryForm').style.display = 'none';
    
    // 滚动到结果卡片
    resultCard.scrollIntoView({ behavior: 'smooth' });
}

// 隐藏旧的抽奖结果
function hideOldLotteryResult() {
    const resultCard = document.getElementById('resultCard');
    const lotteryForm = document.getElementById('lotteryForm');
    
    if (resultCard && resultCard.style.display === 'block') {
        console.log('隐藏旧抽奖结果');
        resultCard.style.display = 'none';
        
        // 显示抽奖表单
        if (lotteryForm) {
            lotteryForm.style.display = 'block';
        }
    }
}

// 检查活动状态
function checkLotteryStatus() {
    fetch('/lottery/status')
    .then(response => response.json())
    .then(data => {
        console.log('活动状态:', data);
        const statusElement = document.getElementById('activityStatus');
        
        // 更新状态显示
        if (data.active) {
            statusElement.className = 'badge bg-success';
            statusElement.textContent = '活动进行中';
        } else {
            statusElement.className = 'badge bg-danger';
            statusElement.textContent = '活动暂停';
        }
        
        // 根据活动状态切换页面内容
        updatePageContent(data.active, data.round_number);
    })
    .catch(error => {
        console.error('Error checking status:', error);
        const statusElement = document.getElementById('activityStatus');
        if (statusElement) {
            statusElement.className = 'badge bg-warning';
            statusElement.textContent = '状态未知';
        }
    });
}

// 显示提示消息
function showToast(message, type = 'success') {
    console.log('showToast 被调用:', message, type);
    
    // 使用全局Toast函数
    if (window.LotteryApp && window.LotteryApp.showToast) {
        window.LotteryApp.showToast(message, type);
        return;
    }
    
    // 备用方案：本地Toast处理
    const toastEl = document.getElementById('toastMessage') || document.getElementById('globalToast');
    const toastBody = document.getElementById('toastBody') || document.getElementById('globalToastBody');
    
    if (!toastEl || !toastBody) {
        console.error('Toast elements not found, using alert');
        alert(message);
        return;
    }
    
    console.log('Toast elements found, showing message');
    toastBody.textContent = message;
    
    // 重置类名
    toastEl.className = 'toast';
    if (type === 'error') {
        toastEl.classList.add('bg-danger', 'text-white');
    } else if (type === 'warning') {
        toastEl.classList.add('bg-warning', 'text-dark');
    } else {
        toastEl.classList.add('bg-success', 'text-white');
    }
    
    try {
        if (typeof bootstrap !== 'undefined' && bootstrap.Toast) {
            const toast = new bootstrap.Toast(toastEl);
            toast.show();
            console.log('Bootstrap Toast shown');
        } else {
            console.error('Bootstrap not loaded, using alert');
            alert(message);
        }
    } catch (error) {
        console.error('Error showing toast:', error);
        alert(message);
    }
}

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('页面加载完成，开始初始化...');
    
    // 立即检查状态
    checkLotteryStatus();
    
    // 定期检查活动状态（每5秒）
    setInterval(checkLotteryStatus, 5000);
    
    // 绑定初始表单事件（如果存在）
    bindFormEvents();
});
</script>
{% endblock %}
